<template>
  <div class="app-container">
    <el-card v-show="form.type ===2" style="height: 500px">
      <el-row :gutter="20">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px">
          <el-row :gutter="20" v-show="showSearch">
            <el-form-item label="审核状态" prop="verifyStatus">
              <el-select v-model="queryParams.verifyStatus" filterable placeholder="审核状态" clearable size="mini">
                <el-option v-for="dict in verifyStatusOptions" :key="dict.value" :label="dict.label"
                           :value="+dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="商品状态" prop="status">
              <el-select v-model="queryParams.status" filterable placeholder="商品状态" clearable size="mini">
                <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="+dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="是否上架" prop="publishStatus">
              <el-select v-model="queryParams.publishStatus" filterable placeholder="是否上架" clearable size="mini">
                <el-option v-for="dict in pulishStatusOptions" :key="dict.value" :label="dict.label"
                           :value="+dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="是否新品" prop="newStatus">
              <el-select v-model="queryParams.newStatus" filterable placeholder="是否新品" clearable size="mini">
                <el-option v-for="dict in newStatusOptions" :key="dict.value" :label="dict.label" :value="+dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="是否推荐" prop="recommendStatus">
              <el-select v-model="queryParams.recommendStatus" filterable placeholder="是否推荐" clearable size="mini">
                <el-option v-for="dict in recommendStatusOptions" :key="dict.value" :label="dict.label"
                           :value="+dict.value"/>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="商品名称" prop="name">
                    <el-input v-model="queryParams.name" placeholder="项目名称" clearable size="mini"
                              @keyup.enter.native="handleQuery"/>
                  </el-form-item>
                </el-col>
                <el-col :span="12" class="ub row-right">
                  <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                  <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="12">
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card shadow="hover">
            <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" :height="tableHeight">
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column label="编号" type="index" width="50" align="center"/>
              <el-table-column label="商品名称" prop="name" width="100" align="center"/>
              <el-table-column label="价格" prop="price" width="50" align="center"/>
              <el-table-column label="购买积分" prop="point" width="80" align="center"/>
              <el-table-column label="标签" width="260" align="center">
                <template slot-scope="{row}">
                  <div class="ub main-center" style="margin-left: 20px">
                    <div class="switch-item">
                      <span>上架：</span>
                      <span>
                  <el-tag v-if="row.publishStatus===1" type="success">是</el-tag>
                  <el-tag v-else type="info">否</el-tag>
                </span>
                    </div>
                    <div class="switch-item">
                      <span>新品：</span>
                      <span>
                  <el-tag v-if="row.newStatus===1" type="success">是</el-tag>
                  <el-tag v-else type="info">否</el-tag>
                </span>
                    </div>
                    <div class="switch-item">
                      <span>推荐：</span>
                      <span>
                  <el-tag v-if="row.recommendStatus===1" type="success">是</el-tag>
                  <el-tag v-else type="info">否</el-tag>
                </span>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="销量" prop="sale" width="50" align="center"/>
            </el-table>
          </el-card>
        </el-col>

        <!--  选中的商品  tag标签     -->
        <el-col :span="12">
          <el-card style="height: 280px" shadow="hover">
            <el-tag style="margin-left: 20px;margin-top: 10px" v-for="item in form.productList" :key="item.id"
                    :type="tagTypeList[item.id % 5]" closable @close="removeProduct(item)">
              {{ item.name }}
            </el-tag>
          </el-card>
        </el-col>

      </el-row>
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size"
                  @pagination="getList"/>
    </el-card>
    <el-card style="margin-top: 30px;">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="卡券名称" prop="name">
              <el-input v-model="form.name" clearable placeholder="请输入卡券名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="面值" prop="amount">
              <el-input-number v-model="form.amount" style="width: 100%" controls-position="right" clearable
                               placeholder="请输入面值"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="发行量" prop="publishCount">
              <el-input-number v-model="form.publishCount" style="width: 100%" controls-position="right" clearable
                               placeholder="请输入发行量"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0" p>
            <el-form-item label="使用门槛" prop="minPoint">
              <el-input-number v-model="form.minPoint" style="width: 100%" controls-position="right" clearable
                               placeholder="请输入使用门槛"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="有效期" prop="endTime">
              <el-date-picker v-model="timeRange" style="width: 100%" type="datetimerange" range-separator="至"
                              start-placeholder="开始日期" value-format="yyyy-MM-dd HH:mm:ss" end-placeholder="结束日期"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="优惠券类型" prop="type">
              <el-radio-group v-model="couponType">
                <el-radio v-for="dict in typeOptions" :key="dict.value" :label="+dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <!--指定商品分类-->
          <div v-show="form.type ===1 " style="width: 100%">
            <el-form label-width="100px" :inline="true" size="mini">
              <el-form-item label="选择分类">
                <el-cascader v-model="currentProductCategoryList" clearable filterable placeholder="选择分类"
                             style="width: 100%"
                             :options="productCategoryTreeList"
                             :props="{ expandTrigger: 'hover', value: 'id', label: 'name' }"/>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="addProductCategory">添加</el-button>
              </el-form-item>
              <el-table header-row-class-name="pochi-table-header" :data="form.productCategoryList" stripe border
                        style="width: 100%">
                <el-table-column prop="id" label="分类编号"/>
                <el-table-column prop="name" label="分类名称"/>
                <el-table-column label="操作">
                  <template slot-scope="{row}">
                    <el-button type="text" icon="el-icon-delete" @click="removeProsuctCategory(row)">删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </el-row>
        <el-row :gutter="20" class="ub main-justify" style="margin-top: 30px">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getProductCategoryOptionSelect } from '@a/beauty/productCategory'
import { addCoupon } from '@a/beauty/coupon'
import { listProduct } from '@a/beauty/product'

export default {
  name: 'add',
  inject: ['reload'],
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      tagTypeList: ['', 'success', 'info', 'warning', 'danger'],
      tableHeight: window.innerHeight - 700,
      // 卡券类型
      couponType: 0,
      // 卡券类型
      typeOptions: [],
      // 当前选择的分类
      currentProductCategoryList: [],
      // 分类列表
      productCategoryTreeList: [],
      // 有效期范围
      timeRange: [],
      // 表单参数
      form: {
        id: null,
        name: null,
        amount: null,
        minPoint: null,
        startTime: null,
        endTime: null,
        type: 0,
        publishCount: null,
        // 商品分类集合
        productCategoryList: [],
        // 商品集合
        productList: []
      },
      // 表单校验
      // 表单校验
      rules: {
        name: [
          { required: true, message: '卡券名称不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '卡券类型不能为空', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '面值不能为空', trigger: 'blur' }
        ],
        minPoint: [
          { required: true, message: '门槛积分不能为空', trigger: 'blur' }
        ],
        publishCount: [
          { required: true, message: '发行数量不能为空', trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '有效期不能为空', trigger: 'blur' }
        ]
      },
      // 遮罩层
      loading: true,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: undefined,
        status: undefined,
        publishStatus: undefined,
        newStatus: undefined,
        recommendStatus: undefined,
        verifyStatus: undefined
      },
      // 总条数
      total: 0,
      // 商品表格数据
      list: [],
      // 商品分类 id name
      productCategoryOptions: [],
      // 是否审核数据字典
      verifyStatusOptions: [],
      // 是否推荐
      recommendStatusOptions: [],
      // 是否新品
      newStatusOptions: [],
      // 是否上架
      pulishStatusOptions: [],
      // 商品状态
      statusOptions: []
    }
  },
  created() {
    this.getDictItems('beauty_coupon_type').then(response => {
      this.typeOptions = response.data
      // console.log(this.typeOptions)
    })
    this.getDictItems('beauty_product_verify_status').then(response => {
      this.verifyStatusOptions = response.data
    })
    this.getDictItems('beauty_product_status').then(response => {
      this.statusOptions = response.data
    })
    this.getDictItems('beauty_product_publish_status').then(response => {
      this.pulishStatusOptions = response.data
    })
    this.getDictItems('beauty_product_new_status').then(response => {
      this.newStatusOptions = response.data
    })
    this.getDictItems('beauty_product_recommand_status').then(response => {
      this.recommendStatusOptions = response.data
    })
    this.getProductCategoryOptionSelect()
  },
  watch: {
    couponType(newVal, oldVal) {
      // console.log(newVal)
      // 每次变化 都要置空一下之前的列表
      this.form.productList = []
      this.form.productCategoryList = []
      if (newVal === 2) {
        this.getList()
      }
      this.form.type = newVal
    },
    timeRange: {
      immediate: true,
      deep: true,
      handler: function(newVal) {
        if (newVal && newVal[0]) {
          this.form.startTime = newVal[0]
          this.form.endTime = newVal[1]
        } else {
          this.form.startTime = null
          this.form.endTime = null
        }
      }
    }
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      listProduct(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.loading = false
      })
    },
    // 移除商品
    removeProduct(item) {
      this.form.productList.splice(this.form.productList.indexOf(item), 1)
      // console.log(item)
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if (this.form.productList) {
        if (selection) {
          selection.forEach(sel => {
            if (this.form.productList.find(item => item.id === sel.id)) {
              return
            } else {
              this.form.productList.push(sel)
            }
          })
        }
      }
      // console.log(this.form.productList)
      // this.form.productList = selection
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 移除分类
    removeProsuctCategory(row) {
      // findIndex()函数也是查找目标元素，找到就返回元素的位置，找不到就返回-1。
      // this.form.productCategoryList.splice(
      //   this.form.productCategoryList.findIndex(item => item.id === row.id)
      // )
      this.form.productCategoryList.splice(this.form.productCategoryList.indexOf(row), 1)
    },
    // 获取商品分类列表
    getProductCategoryOptionSelect() {
      getProductCategoryOptionSelect().then(response => {
        //  我们只要二级的 因为在存品牌分类的时候我们只是存二级分类id 和品牌进行关联
        let data = response.data.filter(e => e.level !== 3)
        this.productCategoryTreeList = this.handleTree(data)
      })
    },
    // 指定分类
    addProductCategory() {
      const firstId = this.currentProductCategoryList[0]
      const secondId = this.currentProductCategoryList[1]
      const thirdId = this.currentProductCategoryList[2]
      // console.log(this.currentProductCategoryList)
      // 根据第一个下标找到一级分类
      let name = ''
      // console.log(this.productCategoryTreeList)
      // 获取子节点，根据第一个下标找到一级分类
      this.productCategoryTreeList.forEach(firstc => {
        if (firstc.id === firstId) {
          name += firstc.name
          if (firstc.children) {
            // // 获取子节点，根据第二个下标找到二级分类
            firstc.children.forEach(secondc => {
              if (secondc.id === secondId) {
                name += ' -> ' + secondc.name
                // SUV项目 -> 漆面美容
                let obj = {
                  id: secondc.id,
                  level: secondc.level,
                  name: name,
                  parentId: secondc.parentId
                }
                // console.log(obj)
                // findIndex()函数也是查找目标元素，找到就返回元素的位置，找不到就返回-1。
                if (this.form.productCategoryList.find(item => item.id === obj.id)) {
                  this.msgNoticeError('该分类已存在,不要重复添加')
                  this.currentProductCategoryList = []
                  return
                } else {
                  // 不能重复添加
                  this.form.productCategoryList.push(obj)
                  this.currentProductCategoryList = []
                  return
                }
              }
            })
          } else {
            this.msgNoticeError('当前为一级分类,请选择二级分类')
            this.currentProductCategoryList = []
            return
          }
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // console.log(this.form)
          addCoupon(this.form).then(res => {
            this.msgNoticeSuccess('新增成功')
            this.$router.push('/marketing/coupon')
          })
        }
      })
    },
    // 取消按钮
    cancel() {
      this.$router.back(-1)
      this.reload()
    }
  }
}
</script>

<style scoped>
.switch-item {
  margin-left: 5px;
  font-weight: bolder;
}
</style>
